package router

import (
	"fmt"
	"image"
	"imageConvert/pkg/igc"
	"imageConvert/pkg/mlog"
	"net/http"
	"os"
	"path"
	"strconv"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"github.com/toolkits/pkg/ginx"
)

func apiImageRouter(apiImage *gin.RouterGroup) {
	apiImage.POST("convert", routerConvert)
	apiImage.GET("download/:file", routerDownload)
}

// 图片转换
func routerConvert(c *gin.Context) {
	fileHeader, err := c.FormFile("file")
	ginx.Dangerous(err)
	fileExt := strings.ToLower(path.Ext(fileHeader.Filename))
	switch strings.ToLower(fileExt) {
	case ".png", ".jpg":
	default:
		ginx.Bomb(http.StatusOK, "目前只支持上传PNG和JPG格式")
	}

	toType := c.PostForm("type")
	toMsg := strings.ToLower(toType)
	var recs []image.Rectangle
	switch strings.ToLower(toType) {
	case "bmp":
	case "ico":
		tmpStr := c.PostForm("size")
		toSize, err := strconv.Atoi(tmpStr)
		if err != nil {
			ginx.Bomb(http.StatusOK, "size值[%s]不是整型", tmpStr)
		}
		switch toSize {
		case 16, 24, 32, 48, 64, 96, 128, 256:
			recs = append(recs, image.Rect(0, 0, toSize, toSize))
		default:
			ginx.Bomb(http.StatusOK, "ICO图片大小错误")
		}
		toMsg = fmt.Sprintf("%s[%d]", toMsg, toSize)
	default:
		ginx.Bomb(http.StatusOK, "目前只支持转成BMP和ICO格式")
	}

	id := strings.ReplaceAll(uuid.NewString(), "-", "")
	file, err := fileHeader.Open()
	ginx.Dangerous(err)

	//保存成临时文件，并延迟删除，或下载后删除
	tmpFile := fmt.Sprintf("%s/%s.%s", CovertImagePath, id, toType)
	_, err = os.Stat(CovertImagePath)
	if nil != err {
		err = os.MkdirAll(CovertImagePath, os.ModeDir)
		ginx.Dangerous(err)
	}

	err = igc.Convert2ImageByFile(file, tmpFile, toType, recs...)
	ginx.Dangerous(err)
	defer func(fileName string) {
		go func(delName string) {
			time.Sleep(time.Second * 60 * 5)
			os.Remove(delName)
		}(fileName)
	}(tmpFile)

	mlog.Infof("图片转换：%s to %s", fileHeader.Filename, toMsg)
	ginx.NewRender(c).Data(fmt.Sprintf("%s.%s", id, toType), nil)
}

// 图片下载
func routerDownload(c *gin.Context) {
	fileName := ginx.UrlParamStr(c, "file")
	sourceName := ginx.QueryStr(c, "source", "")
	if sourceName != "" {
		sourceName = igc.ChangeFileExtension(sourceName, path.Ext(fileName))
	} else {
		sourceName = fileName
	}
	fullFileName := fmt.Sprintf("%s/%s", CovertImagePath, fileName)
	if !fileExists(fullFileName) {
		ginx.Dangerous(fmt.Errorf("文件不存在，或是已过期"))
	}
	c.Header("Content-Type", "application/octet-stream")
	c.Header("Content-Disposition", "attachment; filename="+sourceName)
	defer func() {
		os.Remove(fullFileName)
	}()
	mlog.Infof("下载文件：%s", fullFileName)
	c.File(fullFileName)

}

func fileExists(filePath string) bool {
	_, err := os.Stat(filePath)
	if err != nil {
		if os.IsNotExist(err) {
			return false
		}
	}
	return true
}
